const OpenAI = require('openai');

// OpenAI配置接口
type OpenAIType = typeof OpenAI;
export interface OpenAIConfig {
  apiKey: string;
  organization?: string;
  baseURL?: string;
  timeout?: number;
  maxRetries?: number;
}

// 验证必要的环境变量
const requiredEnvVars = [
  'OPENAI_API_KEY'
];

const missingEnvVars = requiredEnvVars.filter(varName => !process.env[varName]);
if (missingEnvVars.length > 0) {
  console.warn(`⚠️  OpenAI配置不完整，缺少环境变量: ${missingEnvVars.join(', ')}`);
  console.warn(`   AI图像生成功能将无法正常工作，请在.env文件中配置这些变量`);
}

// OpenAI配置
export const openaiConfig: OpenAIConfig = {
  apiKey: process.env.OPENAI_API_KEY || '',
  organization: process.env.OPENAI_ORGANIZATION,
  baseURL: process.env.OPENAI_BASE_URL,
  timeout: parseInt(process.env.OPENAI_TIMEOUT || '60000'), // 60秒超时
  maxRetries: parseInt(process.env.OPENAI_MAX_RETRIES || '3')
};

// 创建OpenAI客户端实例
export const createOpenAIClient = (): any | null => {
  try {
    if (!openaiConfig.apiKey) {
      console.warn('⚠️  OpenAI配置不完整，无法创建客户端');
      return null;
    }

    const client = new OpenAI({
      apiKey: openaiConfig.apiKey,
      organization: openaiConfig.organization,
      baseURL: openaiConfig.baseURL,
      timeout: openaiConfig.timeout,
      maxRetries: openaiConfig.maxRetries
    });

    console.log('✅ OpenAI客户端创建成功');
    return client;
  } catch (error) {
    console.error('❌ 创建OpenAI客户端失败:', error);
    return null;
  }
};

// 导出默认客户端实例
export const openaiClient = createOpenAIClient();

// DALL-E模型配置
export const dalleConfig = {
  model: 'dall-e-3',
  size: '1024x1024' as const,
  quality: 'standard' as const,
  style: 'vivid' as const,
  response_format: 'url' as const
};

// 图像生成提示词模板
export const promptTemplates = {
  roomDesign: {
    'living-room': 'A beautiful modern living room with {style} design style, featuring comfortable seating, elegant lighting, and tasteful decor. High quality interior design photography.',
    living: 'A beautiful modern living room with {style} design style, featuring comfortable seating, elegant lighting, and tasteful decor. High quality interior design photography.',
    bedroom: 'A serene and stylish bedroom with {style} design aesthetic, including a comfortable bed, ambient lighting, and harmonious color scheme. Professional interior photography.',
    kitchen: 'A functional and beautiful kitchen with {style} design elements, modern appliances, elegant countertops, and thoughtful storage solutions. High-end interior design photography.',
    bathroom: 'A luxurious and spa-like bathroom with {style} design features, premium fixtures, elegant tiles, and sophisticated lighting. Professional interior photography.',
    office: 'A productive and inspiring home office with {style} design style, ergonomic furniture, organized workspace, and motivating decor. Modern interior design photography.',
    'dining-room': 'An elegant dining room with {style} design aesthetic, beautiful dining table, comfortable seating, and atmospheric lighting. High-quality interior photography.',
    dining: 'An elegant dining room with {style} design aesthetic, beautiful dining table, comfortable seating, and atmospheric lighting. High-quality interior photography.',
    'game-room': 'A fun and entertaining game room with {style} design elements, comfortable gaming furniture, ambient lighting, and recreational equipment. Modern entertainment space photography.',
    basement: 'A transformed basement space with {style} design aesthetic, comfortable furnishing, proper lighting, and functional layout. Professional basement renovation photography.',
    'outdoor-terrace': 'A beautiful outdoor terrace with {style} design style, comfortable outdoor furniture, ambient lighting, and harmonious landscaping. High-quality outdoor living photography.'
  },
  styles: {
    modern: 'clean lines, minimalist furniture, neutral colors, and contemporary materials',
    traditional: 'classic furniture, warm colors, rich textures, and timeless elegance',
    minimalist: 'simple forms, monochromatic palette, uncluttered spaces, and essential furniture',
    scandinavian: 'light woods, white and neutral tones, cozy textiles, and functional design',
    industrial: 'exposed brick, metal fixtures, dark colors, and urban aesthetic',
    bohemian: 'eclectic patterns, vibrant colors, natural materials, and artistic elements',
    tribal: 'ethnic patterns, natural materials, earthy colors, and cultural artifacts',
    cyberpunk: 'neon lighting, futuristic elements, dark colors with bright accents, and high-tech aesthetic',
    coastal: 'light blues and whites, natural textures, beach-inspired decor, and airy atmosphere',
    professional: 'sophisticated furniture, neutral tones, organized layout, and business-appropriate aesthetic'
  }
};